#include "common_typedef.h"
#include "prj1u.h"
#include <sys/select.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>

ERRCODE InitSocket();

static int g_socket = 0;

void ValeCentralMain()
{
    printf("[%s] enter\n", APP_VALE);
    ERRCODE ret = InitSocket();

    char buffer[128];

    int counter = 0;
    while (ret == ERR_SUCCESS)
    {
        usleep(1000 * 500);
        struct sockaddr_in src;
        socklen_t srcLen = sizeof(src);
        memset(&src, 0, sizeof(src));

        memset(buffer, 0, 128);
        int sz = recvfrom(g_socket, buffer, 128, 0, (struct sockaddr*)&src, &srcLen);
        if (sz > 0){
            buffer[sz] = 0;
            printf("Get Message: %s\n", buffer);
        }
    }
    close(g_socket);
    printf("[%s] left\n", APP_VALE);

    return 0;
}

ERRCODE InitSocket()
{
    //同一台电脑测试，需要两个端口
    int port = 3333;

    // 创建socket
    g_socket = socket(AF_INET, SOCK_DGRAM, 0);
    printf("[%s] socket[%d] create %s\n", APP_VALE, g_socket, g_socket == -1 ? "FAILED" : "SUCCESS");
    if (-1 == g_socket) {
        return ERR_FAILURE;
    }

    // 设置地址与端口
    struct sockaddr_in addr;
    socklen_t addrLen = sizeof(addr);
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

   // Time out
    struct timeval tv = {
        .tv_sec  = 0,
        .tv_usec = 50 * 1000
    };
    setsockopt(g_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(struct timeval));

    // Bind 端口，用来接受之前设定的地址与端口发来的信息,作为接受一方必须bind端口，并且端口号与发送方一致
    int bindRet = bind(g_socket, (struct sockaddr*)&addr, addrLen);
    printf("[%s] socket[%d] bind port [%d] %s\n", APP_VALE, g_socket, port, bindRet == -1 ? "FAILED" : "SUCCESS");
    if (bindRet == -1) {
        close(g_socket);
        return ERR_BINDERR;
    }
    return ERR_SUCCESS;
}

void ValeCentralExit()
{

}